package org.ruoyi.common.dhuman.utils.v1;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.kevinsawicki.http.HttpRequest;
import org.ruoyi.common.dhuman.utils.v1.vo.VideoVo;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * <p>Name: Video</p>
 * <p>Description: Video合成类</p>
 * <p>Author: </p>
 * <p>Date: 2024</p>
 **/
public class Video {


	public Video(String appid, String appSecret, String endpointCreate, String endpointStatus) {
		this.appid = appid;
		this.appSecret = appSecret;
		this.endpointCreate = endpointCreate;
		this.endpointStatus = endpointStatus;
	}

	public String appid;
	public String appSecret;
	public String endpointCreate;
	public String endpointStatus;

    public String sign(int timestamp) {
        String serial = this.appid + timestamp + this.appSecret;
        String sign = DigestUtils.md5DigestAsHex(serial.getBytes(StandardCharsets.UTF_8));
        return "MD5 " + sign.toUpperCase();
    }

    public String createVideo(String audio_url, String model_Id, String callback_url, String video_info) {
        // 构造请求体
        VideoVo requestVO = new VideoVo();
        requestVO.setAudio_url(audio_url);
        requestVO.setModel_id(model_Id);
        requestVO.setCallback_url(callback_url);
        requestVO.setVideo_info(video_info);

        ObjectMapper objectMapper = new ObjectMapper();
        int timestamp = (int) (System.currentTimeMillis() / 1000L);
        
        try {
            String payload = objectMapper.writeValueAsString(requestVO);
			System.out.println("payload: " + payload);
            String sign = this.sign(timestamp);
            HttpRequest httpRequest = HttpRequest.post(this.endpointCreate)
                    .contentType("application/json", "utf-8")
                    .header("X-Deepsound-Appid", this.appid)
                    .header("X-Deepsound-Timestamp", timestamp)
                    .header("X-Deepsound-Sign", sign)
                    .send(payload);
			String response = httpRequest.body();
            System.out.println(response);
            return response;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

	public String queryVideo(String video_Id) {
		ObjectMapper objectMapper = new ObjectMapper();
		int timestamp = (int) (System.currentTimeMillis() / 1000L);

		String url = this.endpointStatus + "?video_id=" + video_Id;
		System.out.println("url: " + url);
		String sign = this.sign(timestamp);
		HttpRequest httpRequest = HttpRequest.get(url)
			.contentType("application/json", "utf-8")
			.header("X-Deepsound-Appid", this.appid)
			.header("X-Deepsound-Timestamp", timestamp)
			.header("X-Deepsound-Sign", sign);
		String response = httpRequest.body();
		System.out.println(response);
		return response;
	}
}
